// @Author EthanScriptOn
// @Desc
package connect

import (
	"database/sql"
	"fmt"
	"gitee.com/fatzeng/srf_switch_basic_components/util"
	"gitee.com/fatzeng/srf_switch_expansion_package/detect"
)

var MysqlQueryDB *util.OnceInitializer

var MysqlQueryDBChecker = func() (isInvalid bool) {
	consumer, err := generateMysqlQueryDB()
	if err != nil {
		return true
	}
	if err = consumer.Ping(); err != nil {
		_ = consumer.Close()
		return true
	}
	return false
}

var MysqlQueryDBRecover = func() (err error) {
	MysqlQueryDB.Reset()
	_, err = MysqlQueryDB.Get()
	return err
}

var MysqlQueryDBMonitor = detect.GenerateResourceMonitor("mysql_query", true, MysqlQueryDBChecker, MysqlQueryDBRecover, detect.MonitorFunctionInstance)

func GetMysqlQueryDB() (instance *sql.DB, err error) {
	defer detect.BackendHealthChecker.AddResource(MysqlQueryDBMonitor)
	return generateMysqlQueryDB()
}

func generateMysqlQueryDB() (consumer *sql.DB, err error) {
	if MysqlQueryDB == nil {
		return nil, fmt.Errorf("the MysqlQueryDB initialization required")
	}
	instanceInter, err := MysqlQueryDB.Get()
	if err != nil {
		return nil, err
	}
	instance, ok := instanceInter.(*sql.DB)
	if !ok {
		return nil, fmt.Errorf("the instance is not of type *sql.DB")
	}
	return instance, nil
}

var MysqlExecDB *util.OnceInitializer

var MysqlExecDBChecker = func() (isInvalid bool) {
	consumer, err := generateMysqlExecDB()
	if err != nil {
		return true
	}
	if err = consumer.Ping(); err != nil {
		_ = consumer.Close()
		return true
	}
	return false
}

var MysqlExecDBRecover = func() (err error) {
	MysqlExecDB.Reset()
	_, err = MysqlExecDB.Get()
	return err
}

var MysqlExecDBMonitor = detect.GenerateResourceMonitor("mysql_exec", true, MysqlExecDBChecker, MysqlExecDBRecover, detect.MonitorFunctionInstance)

func GetMysqlExecDB() (instance *sql.DB, err error) {
	defer detect.BackendHealthChecker.AddResource(MysqlExecDBMonitor)
	return generateMysqlExecDB()
}

func generateMysqlExecDB() (consumer *sql.DB, err error) {
	if MysqlExecDB == nil {
		return nil, fmt.Errorf("the MysqlExecDB initialization required")
	}
	instanceInter, err := MysqlExecDB.Get()
	if err != nil {
		return nil, err
	}
	instance, ok := instanceInter.(*sql.DB)
	if !ok {
		return nil, fmt.Errorf("the instance is not of type *sql.DB")
	}
	return instance, nil
}
